<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <el-button type="primary">添加角色</el-button>
      <!-- 角色列表 -->
      <el-table :data="rolesList" border stripe>
        <el-table-column label="明细" type="expand">
          <template slot-scope="scope">
            <!-- 一级权限 -->
            <el-row v-for="(item1,i1) in scope.row.children" :key="item1.id"
              :class="{bdbottom:true,bdtop:i1==0,vcenter:true}">
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row,item1.id)">{{ item1.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <!-- 二级权限 -->
                <el-row v-for="(item2,i2) in item1.children" :key="item2.id" :class="{bdtop:i2!=0,vcenter:true}">
                  <el-col :span="6">
                    <el-tag closable type="success" @close="removeRightById(scope.row,item2.id)">{{ item2.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <!-- 三级权限 -->
                    <el-tag closable type="warning" v-for="(item3,i3) in item2.children" :key="item3.id"
                      @close="removeRightById(scope.row,item3.id)">
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="序号" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditDialog(scope.row)">编辑</el-button>
            <el-button type="danger" size="mini" icon="el-icon-delete">删除</el-button>
            <el-button type="warning" size="mini" icon="el-icon-setting" @click="showRightDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限 -->
    <el-dialog title="分配权限" :visible.sync="rightDialogVisible" width="50%" @close="rightDialogClosed">
      <!-- 树形控件 -->
      <el-tree :data="rightsList" show-checkbox node-key="id" :props="treeProps" default-expand-all :default-checked-keys="defaultKeys" ref="treeRef">
      </el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="rightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
	data() {
		return {
			rolesList: [],
			rightDialogVisible: false,
			rightsList: [],
			treeProps:{
				label:'authName',
				children:'children'
			},
			defaultKeys:[],
			// 当前要分配权限的角色id
			roleId:''
		}
	},
	created() {
		this.getRolesList()
	},
	methods: {
		// 获取角色列表
		async getRolesList() {
			const { data: res } = await this.$http.get('roles')
			this.rolesList = res.data
			console.log(this.rolesList)
		},
		// 删除角色下指定的权限
		removeRightById(role, rightId) {
			this.$confirm('确定要删除该权限吗？', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(async () => {
					const { data: res } = await this.$http.delete(
						`roles/${role.id}/rights/${rightId}`
					)
					if (res.meta.status != 200) {
						return this.$message.error('删除权限失败！')
					}
					//  this.getRolesList() // 不建议重新获取所有角色列表，会导致页面刷新
					role.children = res.data // 重新设置当前角色下最新的权限数据即可
				})
				.catch(() => {
					this.$message.info('已取消删除')
				})
		},
		// 显示分配权限的对话框
		async showRightDialog(role) {
			// 获取所有权限
			const { data: res } = await this.$http.get('rights/tree')
			this.rightsList = res.data

			// 获取角色下所有三级权限的id
			this.getLeafKeys(role)
			console.log(this.defaultKeys)

			this.roleId = role.id
			this.rightDialogVisible = true
		},
		getLeafKeys(node){
			// 判断是否为三级权限
			if(!node.children){
				return this.defaultKeys.push(node.id)
			}
			// 如果不是三级权限，则递归操作
			node.children.forEach(item => {
				this.getLeafKeys(item)
			})
		},
		rightDialogClosed(){
			// 关闭对话框时，清空选中的节点id值数组
			this.defaultKeys = []
		},
		// 分配权限
		async allotRights(){
			const keys = this.$refs.treeRef.getCheckedKeys().concat(this.$refs.treeRef.getHalfCheckedKeys())
			const idStr = keys.join(',')

			const {data:res} = await this.$http.post(`roles/${this.roleId}/rights`,{ rids: idStr })
			if(res.meta.status !== 200){
				return this.$message.error('分配权限失败！')
			}
			this.rightDialogVisible = false 
			this.getRolesList()
			this.$message.success('分配权限成功！')
		}
	},
}
</script>

<style lang="less" scoped>
.el-tag {
	margin: 6px;
}
.bdtop {
	border-top: 1px solid #eee;
}
.bdbottom {
	border-bottom: 1px solid #eee;
}
.vcenter {
	display: flex;
	align-items: center;
}
</style>